package com.beiding.hotcode;

import java.util.List;

class MyOrderedClassLoader extends ClassLoader {

    private MapClassLoader mapClassLoader;

    private ClassLoader[] parents;

    //给定多个父类加载器
    MyOrderedClassLoader(MapClassLoader mapClassLoader, ClassLoader... parents) {
        this.mapClassLoader = mapClassLoader;
        this.parents = parents;
    }

    //  Map<String, Class> loadedClassesMap = new HashMap<>();

    //加载类的时候按照先后顺序,将第一个父类加载器加载到结果返回
    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {

        Class<?> aClass = mapClassLoader.loadClass(name);
        if (aClass != null) {
            return aClass;
        }

        for (ClassLoader parent : parents) {
            try {
                return parent.loadClass(name);
            } catch (ClassNotFoundException ignore) {

            }
        }
        // return super.loadClass(name);

        //使用自己的类加载器进行加载
        return this.getClass().getClassLoader().loadClass(name);

    }

    /*
        对类文件进行局部载入,不需要重复定义
     */

    Class define(ClassFileHolder classFileHolder) {

        byte[] data = classFileHolder.getMainData();
        Class<?> defineClass = defineClass(null, data, 0, data.length);
        mapClassLoader.put(defineClass);
        List<byte[]> aboutClassData = classFileHolder.getAboutClassData();
        for (byte[] aboutClassDatum : aboutClassData) {
            Class<?> aClass = defineClass(null, aboutClassDatum, 0, aboutClassDatum.length);
            mapClassLoader.put(aClass);
        }
        return defineClass;
    }

}
